// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV }) // 使用当前云环境
const TcbRouter = require('tcb-router')
const db = cloud.database()
const _ = db.command;
const crypto = require('crypto')
const axios = require('axios');
const { get } = require('http');

// 生成一个7位的随机数字
function generateRandomUid() {
	let uid = '';
	for (let i = 0; i < 7; i++) {
		uid += Math.floor(Math.random() * 10);
	}
	return uid;
}

// 云函数入口函数
exports.main = async (event, context) => {
	const app = new TcbRouter({ event })
	let { OPENID, APPID } = cloud.getWXContext()
	const { addUser, updateId, updateData, queryData, encryptedData, iv, loginCode, consume, inviteData } = event

	app.use(async (ctx, next) => { //适用于所有的路由
		ctx.data = {} //声明data为一个对象
		await next();
	})

	app.router('login', async (ctx, next) => {
		try {
			// 使用 code 换取 openid 和 session_key
			let appSecret = '2e5631c8a380a71c8a8a2795f60d5804'
			// 使用 code 换取 openid 和 session_key
			const response = await axios.get(
				`https://api.weixin.qq.com/sns/jscode2session?appid=${APPID}&secret=${appSecret}&js_code=${loginCode}&grant_type=authorization_code`
			);
			const { openid, session_key } = response.data;
			// 查询用户是否存在
			const userQuerySnapshot = await db.collection('user').where({ open_id: OPENID }).get()
			if (userQuerySnapshot.data.length > 0) {
				let user = userQuerySnapshot.data[0]
				user.isNewUser = false
				//更新现有的session_key
				await db.collection('user').doc(user._id).update({
					data: {
						session_key
					}
				})
				ctx.body = { code: 200, msg: "成功", data: user }
			} else {
				let uid = generateRandomUid();
				while (true) {
					const userExists = await db.collection('user').where({ uid }).get();
					if (userExists.data.length === 0) break;
					uid = generateRandomUid()
				}
				// 用户不存在，添加新用户
				const addUserResult = await db.collection('user').add({
					data: {
						...addUser,
						open_id: OPENID, // 确保存储用户的 open_id
						uid: uid,
						session_key,
						integral: 100,
						create_time: new Date()
					}
				})
				await db.collection('integral_log').add({
					data: {
						remark: "首次登录获取积分",
						num: 100,
						open_id: OPENID,
						create_time: new Date()
					}
				})
				addUserResult.isNewUser = true
				ctx.body = { code: 200, msg: "成功", data: addUserResult }
			}
		} catch (error) {
			ctx.body = { code: 301, msg: error.message, data: {} }
		}
	})

	app.router('update', async (ctx, next) => {
		try {
			const getData = await db.collection('user').doc(updateId).update({ data: updateData })
			console.log("这是update的getData", getData)
			ctx.data.getResult = getData
			ctx.body = { code: 200, msg: "成功", data: ctx.data.getResult }
		} catch (error) {
			ctx.body = { code: 301, msg: error.message, data: {} }
		}
	})

	app.router('get', async (ctx, next) => {
		try {
			const getData = await db.collection('user').where(queryData).get()
			if (getData.data.length > 0) {
				ctx.data.getResult = getData
				const user = getData.data[0]
				const petIdentify = await db.collection('pet_identify').where({ open_id: OPENID }).get()
				user.historyNum = petIdentify.data.length
				user.favoriteNum = 0
				ctx.body = { code: 200, msg: "成功", data: user }
			} else {
				ctx.body = { code: 301, msg: error.message, data: {} }
			}
		} catch (error) {
			ctx.body = { code: 301, msg: error.message, data: {} }
		}
	})
	app.router('getPhoneNumber', async (ctx, next) => {
		try {
			const sessionKey = await getSessionKeyByOpenid(OPENID)
			if (!sessionKey) {
				ctx.body = { code: 301, msg: "sessionKey非法", data: {} }
			} else {
				let decode
				// 创建 decipher 实例
				const decipher = crypto.createDecipheriv(
					'aes-128-cbc',
					Buffer.from(sessionKey, 'base64'),
					Buffer.from(iv, 'base64')
				)
				// 设置自动填充为 true
				decipher.setAutoPadding(true)
				decoded = decipher.update(encryptedData, 'base64', 'utf8')
				decoded += decipher.final('utf8')
				const userInfo = JSON.parse(decoded)
				ctx.body = { code: 200, msg: '成功', data: userInfo.phoneNumber }
			}
		} catch (error) {
			ctx.body = { code: 301, msg: '失败', data: {} }
		}
	})

	app.router('toShare', async (ctx, next) => {
		try {
			// const today = new Date().toISOString().slice(0, 10) // 获取当前日期
			const getData = await db.collection('user_share').where(inviteData).get()
			if (getData.data.length > 0) {
				//已经被邀请过
				ctx.body = { code: 200, msg: "已被邀请过", data: {} }
			} else {
				await db.collection('user_share').add({
					data: {
						invite_code: inviteData.inviteCode,
						invited_uid: inviteData.invitedUid,
						create_time: new Date()
					}
				})
				
				const queryData = await db.collection('user').where({uid: inviteData.inviteCode}).get()
				if (queryData.data.length > 0) {
					let user = queryData.data[0]
					await db.collection('user').where({uid: inviteData.inviteCode}).update({
						data: {
							integral: _.inc(100)
						}
					})
					await db.collection('integral_log').add({
						data: {
							remark: "分享获取积分",
							num: 100,
							open_id: user.open_id,
							create_time: new Date()
						}
					})
				}
				ctx.body = { code: 200, msg: "邀请成功", data: {} }
			}
		} catch (error) {
			ctx.body = { code: 301, msg: '失败', data: {} }
		}
	})

	app.router('getOrder', async (ctx, next) => {
		try {
			const getData = await db.collection('order').get()
			if (getData.data.length > 0) {
				ctx.body = { code: 200, msg: "成功", data: getData.data }
			} else {
				ctx.body = { code: 301, msg: "无数据", data: {} }
			}
		} catch (error) {
			ctx.body = { code: 301, msg: '失败', data: {} }
		}
	})

	app.router('consumeIntegral', async (ctx, next) => {
		try {
			const getData = await db.collection('user').where({ open_id: OPENID }).get()
			if (getData.data.length > 0) {
				const user = getData.data[0]
				const num = 0 - consume.num
				if (user.integral > consume.num) {
					await db.collection('user').doc(user._id).update({
						data: {
							integral: _.inc(num)
						}
					})
				} else {
					await db.collection('user').doc(user._id).update({
						data: {
							integral: 0
						}
					})
				}
				await db.collection('integral_log').add({
					data: {
						remark: consume.remark,
						num: num,
						open_id: OPENID,
						create_time: new Date()
					}
				})
				ctx.body = { code: 200, msg: "成功", data: {} }
			} else {
				ctx.body = { code: 301, msg: '失败', data: {} }
			}

		} catch (error) {
			ctx.body = { code: 301, msg: error.message, data: {} }
		}
	})

	app.router('integralHistory', async (ctx, next) => {
		try {
			const getData = await db.collection('integral_log').where({ open_id: OPENID }).orderBy('create_time', 'desc').get()
			ctx.body = { code: 200, msg: "成功", data: getData.data }
		} catch (error) {
			ctx.body = { code: 301, msg: error.message, data: {} }
		}
	})

	async function getSessionKeyByOpenid(openid) {
		const userQuerySnapshot = await db.collection('user').where({ open_id: openid }).get()
		if (userQuerySnapshot.data.length > 0) {
			let user = userQuerySnapshot.data[0]
			return user.session_key
		}
		return ""
	}
	return app.serve()
}